import { getCartList, updateCart, deleteCart } from '@/api/cart'

export default {
  namespaced: true,
  state: {
    cartList: []
  },
  actions: {
    async getCartList (context) {
      const { data } = await getCartList()
      data.list.forEach(item => {
        item.isChecked = true
      })
      context.commit('setCartList', data.list)
    },
    // 更新购物车
    async updateCart (context, { goodsId, goodsNum, goodsSkuId }) {
      // 先修改本地
      context.commit('changeCount', { goodsId, goodsNum })
      // 后修改后台
      await updateCart(goodsId, goodsNum, goodsSkuId)
    },
    // 删除购物车
    async deleteCart (context, cartIds) {
      const res = await deleteCart(cartIds)
      console.log(res, cartIds)
      //   context.commit('deleteCart', data.list)
      context.commit('deleteAction', cartIds)
    }
  },
  getters: {
    // 商品总数
    totalNum (state) {
      return state.cartList.reduce((sum, item) => sum + item.goods_num, 0)
    },
    // 选中的商品项
    selectedList (state) {
      return state.cartList.filter(item => item.isChecked)
    },
    // 选中的商品总数
    selectedNum (state, getters) {
      return getters.selectedList.reduce((sum, item) => sum + item.goods_num, 0)
    },
    // 商品总价
    selectedPrice (state, getters) {
      return getters.selectedList.reduce((sum, item) => sum + item.goods.goods_price_max * item.goods_num, 0).toFixed(2)
    },
    isAllChecked (state) {
      return state.cartList.every(item => item.isChecked)
    }
  },
  mutations: {
    setCartList (state, list) {
      state.cartList = list
    },
    toggleChecked (state, goodsId) {
      const item = state.cartList.find(item => item.goods_id === goodsId)
      item.isChecked = !item.isChecked
    },
    toggleAllChecked (state, val) {
      state.cartList.forEach(item => {
        item.isChecked = val
      })
    },
    changeCount (state, { goodsId, goodsNum }) {
      const item = state.cartList.find(item => item.goods_id === goodsId)
      item.goods_num = goodsNum
    },
    // 删除购物车
    deleteAction (state, cartIds) {
      state.cartList = state.cartList.filter(item => !cartIds.includes(item.id))
    }
  }
}
